package com.dycn.service;

import com.dycn.dao.SysUserMapper;
import com.dycn.dao.SysUserRoleMapper;
import com.dycn.dao.TasksActivitiesMapper;
import com.dycn.model.SysUser;
import com.dycn.model.SysUserRole;
import com.dycn.model.TasksActivities;
import com.dycn.util.AppResultData;
import com.dycn.util.Md5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    TasksActivitiesMapper tasksActivitiesMapper;
    SysUser findByPhone(String phone){
        return  sysUserMapper.findByPhone(phone);
    }

    public AppResultData listUser(int page){
        PageHelper.startPage(page,10);
        List<SysUser> sysUserList=sysUserMapper.listUser();
        PageInfo pageInfo=new PageInfo(sysUserList);

        return  AppResultData.success(pageInfo.getSize()+"",pageInfo.getList());
    }

    public  AppResultData saveOrUpdate(SysUser sysUser,Integer roleId){
        if(sysUser.getPassword()!=null){
            sysUser.setPassword(Md5Util.getHtMd5(sysUser.getPassword()));
        }
        if(sysUser.getId()!=null){
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
            SysUserRole sysUserRole=sysUserRoleMapper.findByUserId(sysUser.getId());
            if(sysUserRole.getRoleId()!=roleId){
                sysUserRole.setRoleId(roleId);
                sysUserRoleMapper.updateByPrimaryKeySelective(sysUserRole);
            }
        }else {
            sysUserMapper.insert(sysUser);
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setUserId(sysUser.getId());
            sysUserRole.setRoleId(roleId);
            sysUserRoleMapper.insert(sysUserRole);
        }
        return  AppResultData.successMessage("成功");
    }

    public  SysUser findById(String id){
        return  sysUserMapper.findById(id);
    }

    public  AppResultData listTask(int page,String username,String type,Integer activityId){
        SysUser sysUser=sysUserMapper.findByUsername(username);
        SysUserRole sysUserRole=sysUserRoleMapper.findByUserId(sysUser.getId());
        TasksActivities tasksActivities=new TasksActivities();
        tasksActivities.setType(Integer.parseInt(type));
        if(sysUserRole.getRoleId()==1){
           tasksActivities.setUserId(sysUser.getId()+"");
        }
        PageHelper.startPage(page,10);
       tasksActivities.setActivityId(activityId);
        List<TasksActivities> tasksActivitiesList=tasksActivitiesMapper.lists(tasksActivities);
        PageInfo pageInfo=new PageInfo(tasksActivitiesList);
        return  AppResultData.success(pageInfo.getTotal()+"",pageInfo.getList());

    }

}
